package com.kc.web.controller.business;

import cn.hutool.core.date.DateUtil;
import com.kc.business.domain.BizGoods;
import com.kc.business.domain.dto.BizBasicIndicatorsExportDTO;
import com.kc.business.domain.order.dto.*;
import com.kc.business.domain.order.entity.BizOrderStatistics;
import com.kc.business.domain.query.BizOrderStatisticsQuery;
import com.kc.business.mapper.BizGoodsMapper;
import com.kc.business.service.BizOrderStatisticsDataService;
import com.kc.business.service.IBizBasicIndicatorsService;
import com.kc.common.annotation.Excel;
import com.kc.common.constant.BizBasicIndicatorsConstants;
import com.kc.common.core.domain.AjaxResult;
import com.kc.common.utils.poi.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName BasicIndicatorsController
 * @Description 基础数据统计Controller
 * @Author wangdongliang
 * @Date 2021/6/1 8:56
 */
@RestController
@RequestMapping("/business/basicIndicators")
@Slf4j
public class BizBasicIndicatorsController {

    @Resource
    private BizGoodsMapper bizGoodsMapper;
    @Resource
    private IBizBasicIndicatorsService basicIndicatorsService;
    @Resource
    private BizOrderStatisticsDataService orderStatisticsDataService;
    /**
     * 当天实时数据接口
     * @return
     */
    @PreAuthorize("@ss.hasPermi('business:basicIndicators:currDayData')")
    @GetMapping("/currDayData")
    public AjaxResult currDayData(){
//        BizGoods goods = new BizGoods();
//        List<BizGoods> bizGoodsList = bizGoodsMapper.getAllDate();
//        for(BizGoods bizGoods : bizGoodsList){
//            try {
//                BigDecimal bb = bizGoods.getMarketprice().divide(new BigDecimal(1), 0, BigDecimal.ROUND_HALF_UP);
//                log.info("原金额{}", bizGoods.getMarketprice());
//                bizGoods.setMarketprice(bb);
//                log.info("aaaaa{}", bizGoods);
//                bizGoods.setMarketprice(bb);
//                BizGoods g = new BizGoods();
//                g.setId(bizGoods.getId());
//                g.setMarketprice(bb);
//                bizGoodsMapper.updateByPrimaryKeySelective(bizGoods);
//            }catch (Exception e){
//
//            }
//        }

        String currDate = DateUtil.now().substring(0,10);
        //全站浏览次数
        int browseNum = 0;
        //全站浏览用户量
        int browseUserNum = 0;
        //当天注册用户数
        int userNum = basicIndicatorsService.getUserNumByDate(currDate,BizBasicIndicatorsConstants.DATE_TYPE_DAY);
        //当天订单GMV
        BigDecimal orderMoney = basicIndicatorsService.getOrderMoneyByDate(currDate);
//        List<BizOrderTotalDTO> orderTotalDTOS = new ArrayList<>();
//        orderTotalDTOS.add(new BizOrderTotalDTO(BizBasicIndicatorsConstants.BROWSE_NUM,"",browseNum,0));
//        orderTotalDTOS.add(new BizOrderTotalDTO(BizBasicIndicatorsConstants.BROWSE_USER_NUM,"",browseUserNum,1));
//        orderTotalDTOS.add(new BizOrderTotalDTO(BizBasicIndicatorsConstants.USER_REGISTER_NUM,"",userNum,2));
//        orderTotalDTOS.add(new BizOrderTotalDTO(BizBasicIndicatorsConstants.GMV,"",orderMoney.intValue(),3));

        List<BizOrderStatisticsDataDTO> statisticsDataDTOS = new ArrayList<>();
        statisticsDataDTOS.add(new BizOrderStatisticsDataDTO(BizBasicIndicatorsConstants.BROWSE_NUM,browseNum+"",BizBasicIndicatorsConstants.BROWSE_NUM+browseNum,"",1));
        statisticsDataDTOS.add(new BizOrderStatisticsDataDTO(BizBasicIndicatorsConstants.BROWSE_USER_NUM,browseUserNum+"",BizBasicIndicatorsConstants.BROWSE_USER_NUM+browseUserNum,"",1));
        statisticsDataDTOS.add(new BizOrderStatisticsDataDTO(BizBasicIndicatorsConstants.USER_REGISTER_NUM,userNum+"",BizBasicIndicatorsConstants.USER_REGISTER_NUM+userNum,"",1));
        statisticsDataDTOS.add(new BizOrderStatisticsDataDTO(BizBasicIndicatorsConstants.GMV,orderMoney.intValue()+"",BizBasicIndicatorsConstants.GMV+orderMoney,"",1));
        return AjaxResult.success(statisticsDataDTOS);
    }

    /**
     * 基础指标-数据概述-折线图
     * @param bizOrderStatisticsQuery
     * @return
     */
    @PreAuthorize("@ss.hasPermi('business:basicIndicators:getLineChartByDay')")
    @PostMapping("/getLineChartByDay")
    public AjaxResult getLineChartByDay(@RequestBody  BizOrderStatisticsQuery bizOrderStatisticsQuery){

        //全站浏览次数
        List<String> browseNumList = new ArrayList<>();
        //全站浏览用户量
        List<String> browseUserNum = new ArrayList<>();
        //注册用户数
        List<String> userNumList = new ArrayList<>();
        //新访问用户数
        List<String> newUserNumList = new ArrayList<>();
        //全站GMV(商品交易总额)
        List<String> orderTotalMoney = new ArrayList<>();
        //订单数量
        List<String> orderNum = new ArrayList<>();
        //下单人数
        List<String> orderUserNum = new ArrayList<>();
        //客单价
        List<String> singleUserMoneyList = new ArrayList<>();
        //APP停留时间
        List<String> appVisitTime = new ArrayList<>();

        List<BizOrderStatistics> bizOrderStatisticsList = orderStatisticsDataService.getSaleData(bizOrderStatisticsQuery);
        List<String> dateList = new ArrayList<>();
        int dateType = BizBasicIndicatorsConstants.DATE_TYPE_DAY;
        if(bizOrderStatisticsQuery.getYear() != null){
            dateType = BizBasicIndicatorsConstants.DATE_TYPE_MONTH;
        }
        for(BizOrderStatistics bizOrderStatistics : bizOrderStatisticsList){
            String date = bizOrderStatistics.getYearDay();
            if(bizOrderStatisticsQuery.getYear() != null){
                date = bizOrderStatistics.getCurrMonth();
            }
            dateList.add(date);
            browseNumList.add("0");
            browseUserNum.add("0");
            userNumList.add(basicIndicatorsService.getUserNumByDate(date,dateType)+"");
            newUserNumList.add("0");
            orderNum.add(bizOrderStatistics.getOrderNum()+"");
            orderUserNum.add(bizOrderStatistics.getOrderUserNum()+"");
            orderTotalMoney.add(bizOrderStatistics.getOrderMoney()+"");
            int singleMoney = 0;
            if(bizOrderStatistics.getOrderUserNum() == 0){
                //singleUserMoney.add("0");
            }else{
                singleMoney = (bizOrderStatistics.getOrderMoney().intValue()/bizOrderStatistics.getOrderUserNum());
            }
            singleUserMoneyList.add(singleMoney+"");
        }
        List<BizOrderStatisticsLineChartDataDTO> dataList = new ArrayList<>();
        for (Integer i : bizOrderStatisticsQuery.getIndexes()) {
            if (i.equals(1)) {
                BizOrderStatisticsLineChartDataDTO orderNumInfo = new BizOrderStatisticsLineChartDataDTO("搜索引擎","line","总量",true,null,new BizColorDTO("#9DBCFB"));
                orderNumInfo.setName(BizBasicIndicatorsConstants.BROWSE_NUM);
                orderNumInfo.setData(browseNumList);
                dataList.add(orderNumInfo);
            }else if (i.equals(2)) {
                BizOrderStatisticsLineChartDataDTO orderNumInfo = new BizOrderStatisticsLineChartDataDTO("搜索引擎","line","总量",true,null,new BizColorDTO("#9CE8CA"));
                orderNumInfo.setName(BizBasicIndicatorsConstants.BROWSE_USER_NUM);
                orderNumInfo.setData(browseUserNum);
                dataList.add(orderNumInfo);
            }else if (i.equals(3)) {
                BizOrderStatisticsLineChartDataDTO orderNumInfo = new BizOrderStatisticsLineChartDataDTO("搜索引擎","line","总量",true,null,new BizColorDTO("#9EA9BE"));
                orderNumInfo.setName(BizBasicIndicatorsConstants.USER_REGISTER_NUM);
                orderNumInfo.setData(userNumList);
                dataList.add(orderNumInfo);
            }else if (i.equals(4)) {
                BizOrderStatisticsLineChartDataDTO orderNumInfo = new BizOrderStatisticsLineChartDataDTO("搜索引擎","line","总量",true,null,new BizColorDTO("#FAD773"));
                orderNumInfo.setName(BizBasicIndicatorsConstants.NEW_USER_NUM);
                orderNumInfo.setData(newUserNumList);
                dataList.add(orderNumInfo);
            }else if (i.equals(5)) {
                BizOrderStatisticsLineChartDataDTO orderNumInfo = new BizOrderStatisticsLineChartDataDTO("搜索引擎","line","总量",true,null,new BizColorDTO("#A7DEF4"));
                orderNumInfo.setName(BizBasicIndicatorsConstants.GMV);
                orderNumInfo.setData(orderTotalMoney);
                dataList.add(orderNumInfo);
            }else if (i.equals(6)) {
                BizOrderStatisticsLineChartDataDTO orderNumInfo = new BizOrderStatisticsLineChartDataDTO("搜索引擎","line","总量",true,null,new BizColorDTO("#BEA9DF"));
                orderNumInfo.setName(BizBasicIndicatorsConstants.ORDER_NUM);
                orderNumInfo.setData(orderNum);
                dataList.add(orderNumInfo);
            }else if (i.equals(7)) {
                BizOrderStatisticsLineChartDataDTO orderNumInfo = new BizOrderStatisticsLineChartDataDTO("搜索引擎","line","总量",true,null,new BizColorDTO("#FFC494"));
                orderNumInfo.setName(BizBasicIndicatorsConstants.ORDER_USER_NUM);
                orderNumInfo.setData(orderUserNum);
                dataList.add(orderNumInfo);
            }else if (i.equals(8)) {
                BizOrderStatisticsLineChartDataDTO orderNumInfo = new BizOrderStatisticsLineChartDataDTO("搜索引擎","line","总量",true,null,new BizColorDTO("#F1A492"));
                orderNumInfo.setName(BizBasicIndicatorsConstants.SINGLE);
                orderNumInfo.setData(singleUserMoneyList);
                dataList.add(orderNumInfo);
            }else if (i.equals(8)) {
                BizOrderStatisticsLineChartDataDTO orderNumInfo = new BizOrderStatisticsLineChartDataDTO("搜索引擎","line","总量",true,null,new BizColorDTO("#7DC2C2"));
                orderNumInfo.setName(BizBasicIndicatorsConstants.APP_VISIT_TIME);
                orderNumInfo.setData(appVisitTime);
                dataList.add(orderNumInfo);
            }
        }
        Map<String,Object> map = new HashMap<>();
        map.put("dateList",dateList);
        map.put("list",dataList);

        return AjaxResult.success(map);
    }

    /**
     * 基础指标-数据概述
     * @param bizOrderStatisticsQuery
     * @return
     */
    @PreAuthorize("@ss.hasPermi('business:basicIndicators:dateOverview')")
    @PostMapping("/dateOverview")
    public AjaxResult dateOverview(BizOrderStatisticsQuery bizOrderStatisticsQuery){
        //全站浏览次数
        int browseNum = 0;
        //全站浏览用户量
        int browseUserNum = 0;
        //注册用户数
        int userNum = 0;
        //新访问用户数
        int newUserNum = 0;
        //全站GMV(商品交易总额)
        BigDecimal orderTotalMoney = new BigDecimal(0);
        //订单数量
        int orderNum = 0;
        //下单人数
        int orderUserNum = 0;
        //客单价
        int singleUserMoney = 0;
        //APP停留时间
        int appVisitTime = 0;
        int dateType = BizBasicIndicatorsConstants.DATE_TYPE_DAY;
        if(bizOrderStatisticsQuery.getYear() != null){
            dateType = BizBasicIndicatorsConstants.DATE_TYPE_MONTH;
        }
        List<BizOrderStatistics> bizOrderStatisticsList = orderStatisticsDataService.getSaleData(bizOrderStatisticsQuery);
        for(BizOrderStatistics bizOrderStatistics : bizOrderStatisticsList){
            String date = bizOrderStatistics.getYearDay();
            if(bizOrderStatisticsQuery.getYear() != null){
                date = bizOrderStatistics.getCurrMonth();
            }
            browseNum += 0;
            browseUserNum += 0;
            userNum += basicIndicatorsService.getUserNumByDate(date,dateType);
            newUserNum += 0;
            orderNum += bizOrderStatistics.getOrderNum();
            orderUserNum += bizOrderStatistics.getOrderUserNum();
            orderTotalMoney = orderTotalMoney.add(bizOrderStatistics.getOrderMoney());
            int singleMoney = 0;
            if(bizOrderStatistics.getOrderUserNum() == 0){
                //singleUserMoney.add("0");
            }else{
                singleMoney = (bizOrderStatistics.getOrderMoney().intValue()/bizOrderStatistics.getOrderUserNum());
            }
            singleUserMoney += singleMoney;
        }

        List<BizOrderStatisticsDataDTO> orderStatisticsDataDTOList = new ArrayList<>();
        orderStatisticsDataDTOList.add(new BizOrderStatisticsDataDTO(BizBasicIndicatorsConstants.BROWSE_NUM,browseNum+"",BizBasicIndicatorsConstants.BROWSE_NUM+browseNum,"#9DBCFB",1));
        orderStatisticsDataDTOList.add(new BizOrderStatisticsDataDTO(BizBasicIndicatorsConstants.BROWSE_USER_NUM,browseUserNum+"",BizBasicIndicatorsConstants.BROWSE_USER_NUM+browseNum,"#9CE8CA",2));
        orderStatisticsDataDTOList.add(new BizOrderStatisticsDataDTO(BizBasicIndicatorsConstants.USER_REGISTER_NUM,userNum+"",BizBasicIndicatorsConstants.USER_REGISTER_NUM+browseNum,"#9EA9BE",3));
        orderStatisticsDataDTOList.add(new BizOrderStatisticsDataDTO(BizBasicIndicatorsConstants.NEW_USER_NUM,newUserNum+"",BizBasicIndicatorsConstants.NEW_USER_NUM+browseNum,"#FAD773",4));
        orderStatisticsDataDTOList.add(new BizOrderStatisticsDataDTO(BizBasicIndicatorsConstants.GMV,orderTotalMoney+"",BizBasicIndicatorsConstants.GMV+orderTotalMoney,"#A7DEF4",5));
        orderStatisticsDataDTOList.add(new BizOrderStatisticsDataDTO(BizBasicIndicatorsConstants.ORDER_NUM,orderNum+"",BizBasicIndicatorsConstants.ORDER_NUM+orderNum,"#BEA9DF",6));
        orderStatisticsDataDTOList.add(new BizOrderStatisticsDataDTO(BizBasicIndicatorsConstants.ORDER_USER_NUM,orderUserNum+"",BizBasicIndicatorsConstants.ORDER_USER_NUM+orderUserNum,"#FFC494",7));
        orderStatisticsDataDTOList.add(new BizOrderStatisticsDataDTO(BizBasicIndicatorsConstants.SINGLE,singleUserMoney+"",BizBasicIndicatorsConstants.SINGLE+singleUserMoney,"#F1A492",8));
        orderStatisticsDataDTOList.add(new BizOrderStatisticsDataDTO(BizBasicIndicatorsConstants.APP_VISIT_TIME,appVisitTime+"",BizBasicIndicatorsConstants.APP_VISIT_TIME+appVisitTime,"#7DC2C2",9));
        return AjaxResult.success(orderStatisticsDataDTOList);
    }

    /**
     * 数据下载
     * @return
     */
    @PreAuthorize("@ss.hasPermi('business:basicIndicators:download')")
    @GetMapping("/download")
    public AjaxResult download(BizOrderStatisticsQuery bizOrderStatisticsQuery, HttpServletResponse response){
        //全站浏览次数
        List<String> browseNumList = new ArrayList<>();
        //全站浏览用户量
        List<String> browseUserNum = new ArrayList<>();
        //注册用户数
        List<String> userNumList = new ArrayList<>();
        //新访问用户数
        List<String> newUserNumList = new ArrayList<>();
        //全站GMV(商品交易总额)
        List<String> orderTotalMoney = new ArrayList<>();
        //订单数量
        List<String> orderNum = new ArrayList<>();
        //下单人数
        List<String> orderUserNum = new ArrayList<>();
        //客单价
        List<String> singleUserMoneyList = new ArrayList<>();
        //APP停留时间
        List<String> appVisitTime = new ArrayList<>();

        List<BizOrderStatistics> bizOrderStatisticsList = orderStatisticsDataService.getSaleData(bizOrderStatisticsQuery);
        List<String> dateList = new ArrayList<>();
        int dateType = BizBasicIndicatorsConstants.DATE_TYPE_DAY;
        if(bizOrderStatisticsQuery.getYear() != null){
            dateType = BizBasicIndicatorsConstants.DATE_TYPE_MONTH;
        }
        for(BizOrderStatistics bizOrderStatistics : bizOrderStatisticsList){
            String date = bizOrderStatistics.getYearDay();
            if(bizOrderStatisticsQuery.getYear() != null){
                date = bizOrderStatistics.getCurrMonth();
            }
            dateList.add(date);
            browseNumList.add("0");
            browseUserNum.add("0");
            userNumList.add(basicIndicatorsService.getUserNumByDate(date,dateType)+"");
            newUserNumList.add("0");
            orderNum.add(bizOrderStatistics.getOrderNum()+"");
            orderUserNum.add(bizOrderStatistics.getOrderUserNum()+"");
            orderTotalMoney.add(bizOrderStatistics.getOrderMoney()+"");
            int singleMoney = 0;
            if(bizOrderStatistics.getOrderUserNum() == 0){
                //singleUserMoney.add("0");
            }else{
                singleMoney = (bizOrderStatistics.getOrderMoney().intValue()/bizOrderStatistics.getOrderUserNum());
            }
            singleUserMoneyList.add(singleMoney+"");
            appVisitTime.add("0");
        }
        //数据导出使用
        List<BizBasicIndicatorsExportDTO> exportDataDTOS = new ArrayList<>();
        int len = dateList.size();
        for (int i = 0;i<len;i++){
            BizBasicIndicatorsExportDTO indicatorsExportDTO = new BizBasicIndicatorsExportDTO(dateList.get(i),
                    browseNumList.get(i),
                    browseUserNum.get(i),
                    userNumList.get(i),
                    newUserNumList.get(i),
                    orderTotalMoney.get(i),
                    orderNum.get(i),
                    orderUserNum.get(i),
                    singleUserMoneyList.get(i),
                    appVisitTime.get(i));
            exportDataDTOS.add(indicatorsExportDTO);
        }
        ExcelUtil<BizBasicIndicatorsExportDTO> util = new ExcelUtil<>(BizBasicIndicatorsExportDTO.class);
        Workbook workbook = null;
        try {
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            workbook = util.exportExcelWithoutPersist(exportDataDTOS, "统计表");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", String.format("attachment;filename=%s.xlsx",
                    URLEncoder.encode(String.format("统计表"),
                            "UTF-8")));
            response.flushBuffer();
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        } finally {
            if (null != workbook) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return AjaxResult.success();
    }

}
